package com.loveling.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.io.*;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: liangjiefa
 * Date: 2017/6/4 22:35
 * To change this template use File | Settings | File Templates.
 */

@Controller
public class FileUploadController {

    @RequestMapping(value = "/file")
    public String file(){
        return "/file";
    }

    @RequestMapping(value = "/upload")
    @ResponseBody
    public String handleFileUpload(@PathParam("file")MultipartFile file){
        if(!file.isEmpty()){
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return"上传成功";
        }else {
            return"上传失败";
        }
    }

    //访问：http://127.0.0.1:8080/mutifile
    @RequestMapping(value = "/mutifile", method = RequestMethod.GET)
    public String provideUploadInfo1() {
        return "/mutifile";
    }

    @PostMapping(value="/batch/upload")
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request){
        List<MultipartFile> fileList = ((MultipartHttpServletRequest)request).getFiles("file");
        MultipartFile file =null;
        BufferedOutputStream stream = null;
        for(int i =0;i<fileList.size();i++){
            file = fileList.get(i);
            if(!file.isEmpty()){
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                } catch (IOException e) {
                    stream =  null;
                    return "You failed to upload " + i + " => " + e.getMessage();
                }
            }else {
                return "You failed to upload " + i + " because the file was empty.";
            }
        }
        return  "upload successful";
    }

}
